package org.ssssssss.magicapi.mock;

import cn.hutool.core.util.StrUtil;
import org.apache.commons.lang3.StringUtils;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class MockJsUtils {

    /**
     * Javascript执行引擎
     */
    public static final ScriptEngine MOCK_JS_ENGINE;
    /**
     * mockjs的资源路径
     */
    private static final String MOCK_JS_PATH = "js/mock-min.js";

    static {
        MOCK_JS_ENGINE = new ScriptEngineManager().getEngineByName("js");
        try (
                InputStream mockJs = MockJsUtils.class.getClassLoader().getResourceAsStream(MOCK_JS_PATH);
                InputStreamReader reader = new InputStreamReader(mockJs)
        ) {
            MOCK_JS_ENGINE.eval(reader);
        } catch (ScriptException | IOException e) {
            e.printStackTrace();
        }
    }
    public static String mock(String template) {
        String result = StringUtils.trimToEmpty(template);
        if (isJson(result)) {
            try {
                result = MOCK_JS_ENGINE.eval("JSON.stringify(Mock.mock(" + result + "))").toString();
            } catch (ScriptException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public static boolean isJson(String str){
        return isJsonObj(str) || isJsonAarry(str);
    }

    public static boolean isJsonObj(String str){
        return StrUtil.isBlank(str) ? false : StrUtil.isWrap(str.trim(),'{','}');
    }

    public static boolean isJsonAarry(String str){
        return StrUtil.isBlank(str) ? false : StrUtil.isWrap(str.trim(),'[',']');
    }

    public static void main(String[] args) {
        String input = "{\n" +
                "    \"user|2\": [{\n" +
                "        'name': '@cname', \n" +
                "        'id|+1': 1\n" +
                "    }]\n" +
                "}";
        /*{
            "user|2": [{
            'name': '@cname',
                    'id|+1': 1
        }]
        }*/

        String output = MockJsUtils.mock(input);
        System.out.println(output);
    }
}